<template>
  <div class="question-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 头部按钮 -->
        <div class="btn_wrapper">
          <span style="font-size: 12px; color: pink"
            >说明：目前支持学科和关键字条件筛选</span
          >
          <el-button
            type="success"
            size="small"
            icon="el-icon-edit"
            @click="$router.push('/questions/new')"
            >新增试题</el-button
          >
        </div>

        <!-- 筛选表单 -->
        <el-form
          :model="requestParameters"
          ref="requestParameters"
          label-width="80px"
        >
          <div class="filter-container">
            <el-row>
              <el-col :span="6">
                <el-form-item label="学科">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.subjectID"
                    placeholder="请选择"
                    @change="handleSubject"
                  >
                    <el-option
                      v-for="item in subjectList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="二级目录">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.catalogID"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in twoLevelDirectoryList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标签">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.tags"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in tagsList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关键字">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.keyword"
                    placeholder="根据题干搜索"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="试题类型">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.questionType"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in questionType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="难度">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.difficulty"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in difficulty"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="方向">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.direction"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in direction"
                      :key="item.value"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="录入人">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.creatorID"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in EntryUserList"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="题目备注">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.remarks"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="企业简称">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.shortName"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="城市">
                  <el-col :span="12">
                    <el-select
                      class="filter-item"
                      style="width: 100%"
                      v-model="requestParameters.province"
                      placeholder="请选择"
                      @change="handleProvince"
                    >
                      <el-option
                        v-for="(item, index) in province"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="12">
                    <el-select
                      class="filter-item"
                      style="width: 100%"
                      v-model="requestParameters.city"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, index) in cityData"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item style="text-align: right">
                  <el-button size="small" @click="resetForm">清除</el-button>
                  <el-button size="small" type="primary" @click="handleFilter"
                    >搜索</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <!-- Tabs 标签页 -->
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="待审核" name="0"></el-tab-pane>
          <el-tab-pane label="已审核" name="1"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
        </el-tabs>

        <!-- 数据记录 -->
        <el-alert
          v-if="alertText !== ''"
          :title="alertText"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>

        <!-- 表格 -->
        <el-table
          :data="choiceList"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="试题编号" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学科" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column label="目录" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.catalog }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="questionType"
            label="题型"
            width="120"
            :formatter="formatQuestionType"
          ></el-table-column>
          <el-table-column label="题干" width="280">
            <template slot-scope="scope">
              <span v-html="scope.row.question"></span>
            </template>
          </el-table-column>
          <el-table-column label="录入时间" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | parseTimeByString }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="difficulty"
            label="难度"
            :formatter="formatDifficulty"
            width="80"
          ></el-table-column>
          <el-table-column prop="creator" label="录入人" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.creator }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="chkState"
            label="审核状态"
            :formatter="formatChkType"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="chkRemarks"
            label="审核意见"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="chkUser"
            label="审核人"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="publishState"
            label="发布状态"
            :formatter="formatPublishType"
            width="150"
          ></el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template v-slot="{ row }">
              <el-button type="text" @click="handlePreview(row.id)"
                >预览</el-button
              >
              <!-- 0待审核,审核按钮可以用,  1已审核2已拒绝,审核状态不能用, null -->
              <el-button
                type="text"
                :disabled="row.chkState !== 0"
                @click="open(row)"
                >审核</el-button
              >
              <!-- 试题状态1是上架,修改禁用,0是已下架修改启用 -->
              <el-button
                type="text"
                :disabled="row.publishState === 1"
                @click="
                  $router.push({
                    path: '/questions/new',
                    query: { id: row.id },
                  })
                "
                >修改</el-button
              >
              <!-- 0代表下架1代表上架 -->
              <el-button type="text" @click="changeIsDown(row)">{{
                row.publishState === 1 ? "下架" : "上架"
              }}</el-button>
              <!-- 上架状态的话删除不可点 -->
              <el-button
                type="text"
                :disabled="row.publishState === 1"
                @click="handleDelete(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <div class="pages">
            <el-pagination
              background
              style="margin-top: 20px; text-align: right"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[2, 5, 10, 20, 50]"
              :page-size="pagesize"
              layout="prev, pager, next, sizes, jumper"
              :total="counts"
            >
            </el-pagination>
          </div>
        </div>

        <!-- 查看的弹出层 -->
        <el-dialog title="题目预览" :visible.sync="dialogVisible" width="40%"  @close="isShow = false">
          <div class="title">
            <el-row>
              <el-col :span="6">【题型】：{{ formatQuestionType('', '', questionsDetailObj.questionType, '') }}</el-col>
              <el-col :span="6">【编号】：{{ questionsDetailObj.id }}</el-col>
              <el-col :span="6">【难度】：{{formatDifficulty('', '', questionsDetailObj.difficulty, '') }}</el-col>
              <el-col :span="6">【标签】：{{ questionsDetailObj.tags }}</el-col>
              <el-col :span="6">【学科】：{{ questionsDetailObj.subjectName }}</el-col>
              <el-col :span="6">【目录】：{{ questionsDetailObj.directoryName }}</el-col>
              <el-col :span="6">【方向】：{{ questionsDetailObj.direction }}</el-col>
            </el-row>
          </div>
          <el-divider></el-divider>
          <div class="info">
            【题干】：
            <div style="color: blue">
              <p v-html="questionsDetailObj.question"></p>
            </div>
            <div style="padding-bottom: 5px">
              {{ formatQuestionType('', '', questionsDetailObj.questionType, '') }}
              选项：（以下选中的选项为正确答案）
            </div>
            <!-- 单选 -->
            <div v-if="questionsDetailObj.questionType === '1'">
              <el-radio-group :value="radio">
                <el-radio
                  :label="item.isRight"
                  style="display: block"
                  v-for="item in questionsDetailObj.options"
                  :key="item.id"
                  >{{ item.title }}</el-radio
                >
              </el-radio-group>
            </div>
            <!-- 多选 -->
            <div v-if="questionsDetailObj.questionType === '2'">
              <el-checkbox-group :value="checkboxList">
                <el-checkbox
                  :label="item.isRight"
                  style="display: block"
                  v-for="item in questionsDetailObj.options"
                  :key="item.id"
                  >{{ item.title }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <!-- 简答题 -->
            <div v-if="questionsDetailObj.questionType === '3'">
              <span v-html="questionsDetailObj.question"></span>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="answer">
            【参考答案】：<el-button type="danger" size="small" @click="isShow = true">视频答案预览</el-button>
            <br />
            <video v-if="isShow" :src="questionsDetailObj.videoURL" controls style="width: 100%"></video>
            <!-- <video v-if="isShow" src="http://vjs.zencdn.net/v/oceans.mp4" controls style="width:100%"></video> -->
          </div>
          <el-divider></el-divider>
          <div class="analysis">
            【答案解析】：<span v-html="questionsDetailObj.answer"></span>
          </div>
          <el-divider></el-divider>
          <div class="remarks">
            【题目备注】：{{ questionsDetailObj.remarks }}
          </div>

          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </span>
        </el-dialog>

        <!-- 题目审核的弹出层 -->
        <el-dialog
          title="题目审核"
          :visible.sync="checkDialog"
          width="400px"
          @close="closeChkDialog"
        >
          <el-radio v-model="checkRadio" label="1">通过</el-radio>
          <el-radio v-model="checkRadio" label="2">拒绝</el-radio>
          <el-form style="margin-top: 20px; width: 360px">
            <el-form-item>
              <el-input
                placeholder="请输入审核意见"
                type="textarea"
                v-model="chkRemarks"
              ></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="closeChkDialog">取消</el-button>
            <el-button type="primary" @click="handleCheck">确认</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as subjectSimple } from '@/api/hmmm/subjects'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as entryUser } from '@/api/base/users'
import {
  questionType,
  difficulty,
  direction,
  publishType,
  chkType
} from '@/api/hmmm/constants'
import {
  choice as choiceList,
  detail as questionsDetail,
  remove as questionsRemove,
  choicePublish,
  choiceCheck
} from '@/api/hmmm/questions'

export default {
  data () {
    return {
      requestParameters: {

      },

      subjectList: [], // 学科列表
      twoLevelDirectoryList: [], // 二级目录列表
      tagsList: [], // 标签列表

      province: [],
      cityData: [],

      EntryUserList: [], // 录入人渲染列表
      questionType, // 试题类型列表
      difficulty, // 难度列表
      direction, // 方向列表

      choiceList: [], // 精选题库列表
      alertText: '',

      page: 1,
      pagesize: 5,
      counts: 0,

      listLoading: true,
      dialogVisible: false,
      radio: 1, // 单选框
      checkboxList: [1], // 多选框
      questionsDetailObj: {},
      isShow: false,
      activeName: 'all',
      chkRemarks: '',

      checkDialog: false,
      checkRadio: '1',

      selectedQuestionId: '',
      selectedParameters: { }
      // subjectID: '', keyword: ''
    }
  },
  created () {
    this.getSubjectList() // 获取学科简单列表
    this.getCityData() // 获取城市列表
    this.getEntryUser() // 获取录入人
    this.getChoiceList() // 获取精选题库列表
  },
  methods: {
    // 获取学科简单列表
    async getSubjectList () {
      const res = await subjectSimple()
      // console.log(res)
      this.subjectList = res.data
    },
    // 选学科获取到二级目录,标签
    handleSubject (subjectID) {
      this.getDirectoryList(subjectID)
      this.gettagsList(subjectID)
      // 清空 目录和标签
      this.twoLevelDirectoryList = ''
      this.tagsList = ''
    },
    // 获取目录详情列表
    async getDirectoryList (id) {
      const res = await directorysSimple({ subjectID: id })
      // console.log(res)
      this.twoLevelDirectoryList = res.data
    },
    // 获取标签列表
    async gettagsList (id) {
      const res = await tagsSimple({ subjectID: id })
      // console.log(res)
      this.tagsList = res.data
    },
    // 获取省
    getCityData () {
      this.province = provinces()
    },
    // 选省获取到市
    handleProvince (e) {
      this.cityData = citys(e)
    },
    // 页面一加载获取录入人
    async getEntryUser () {
      const { data: res } = await entryUser()
      // console.log(res)
      this.EntryUserList = res
    },

    // 获取精选题库列表
    async getChoiceList () {
      this.listLoading = true
      const res = await choiceList({ pagesize: this.pagesize, page: this.page })
      // console.log(res)
      this.choiceList = res.data.items // 获取数据
      this.counts = res.data.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
      this.listLoading = false
    },
    // 格式化题型
    formatQuestionType (row, column, cellValue, index) {
      const res = questionType.find((item) => item.value === +cellValue)
      return res ? res.label : '未知'
    },
    // 格式化难度
    formatDifficulty (row, column, cellValue, index) {
      const res = difficulty.find((item) => item.value === +cellValue)
      return res ? res.label : '未知'
    },
    // 格式化发布状态
    formatPublishType (row, column, cellValue, index) {
      const res = publishType.find((item) => {
        return item.value === +cellValue
      })
      if (res.value === 0 && Number(row.chkState) === 1) {
        return '已下架'
      } else if (res.value === 1 && Number(row.chkState) === 1) {
        return '已发布'
      } else {
        return '待发布'
      }
    },
    // 格式化审核状态
    formatChkType (row, column, cellValue, index) {
      const res = chkType.find((item) => {
        return item.value === +cellValue
      })
      return res ? res.label : '未知'
    },

    // 清除
    resetForm () {
      this.requestParameters = {}
      this.selectedParameters = {}
      this.getChoiceList()
    },
    // 搜索
    async handleFilter () {
      this.page = 1
      this.selectedParameters = { ...this.requestParameters }
      const { data } = await choiceList({
        ...this.selectedParameters,
        page: this.page,
        pagesize: 5
      })
      this.choiceList = data.items
      this.counts = data.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
    },

    // 分页
    async handleSizeChange (newSize) {
      // console.log(`每页 ${newSize} 条`)
      this.pagesize = newSize
      this.page = 1
      if (this.activeName === 'all') {
        const { data: res } = await choiceList({
          ...this.selectedParameters,
          pagesize: this.pagesize,
          page: this.page
        })
        // console.log(res)
        this.choiceList = res.items // 获取数据
        this.counts = res.counts // 获取总条数
      } else {
        const { data: res } = await choiceList({
          ...this.requestParameters,
          chkState: Number(this.activeName),
          pagesize: this.pagesize,
          page: this.page
        })
        // console.log(res)
        this.counts = res.counts // 获取总条数
        this.choiceList = res.items // 获取数据
      }
      this.alertText = `共 ${this.counts} 条记录`
    },
    // 当前页更改
    async handleCurrentChange (newPage) {
      // console.log(`当前页: ${newPage}`)
      this.page = newPage
      if (this.activeName === 'all') {
        const { data: res } = await choiceList({
          ...this.selectedParameters,
          pagesize: this.pagesize,
          page: this.page
        })

        // console.log(res)
        this.counts = res.counts // 获取总条数
        this.choiceList = res.items // 获取数据
      } else {
        const { data: res } = await choiceList({
          ...this.requestParameters,
          chkState: Number(this.activeName),
          pagesize: this.pagesize,
          page: this.page
        })

        // console.log(res)
        this.counts = res.counts // 获取总条数
        this.choiceList = res.items // 获取数据
      }
      this.alertText = `共 ${this.counts} 条记录`
    },

    // 预览
    async handlePreview (id) {
      this.dialogVisible = true
      const res = await questionsDetail({ id })
      // console.log(res)
      this.questionsDetailObj = res.data
    },
    // 删除
    async handleDelete (id) {
      try {
        await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示')
        await questionsRemove({ id })
        this.$message.success('删除成功!')
        // 判断该页面是不是只有一条数据 并且 页码不是第一页
        if (this.choiceList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getChoiceList()
      } catch (err) {
        return err
      }
    },

    // 切换Tabs 标签页
    async handleClick (tab, event) {
      this.page = 1
      if (tab.$options.propsData.name === 'all') {
        const { data } = await choiceList({
          ...this.requestParameters,
          pagesize: this.pagesize,
          page: this.page
        })
        this.choiceList = data.items
        this.counts = data.counts // 获取总条数
        this.alertText = `共 ${this.counts} 条记录`
      } else {
        const { data } = await choiceList({
          ...this.requestParameters,
          chkState: Number(this.activeName),
          pagesize: this.pagesize,
          page: this.page
        })
        this.choiceList = data.items
        this.counts = data.counts // 获取总条数
        this.alertText = `共 ${this.counts} 条记录`
      }
    },

    // 上架下架
    changeIsDown (row) {
      let tips = ''
      // 0是下架了要改为上架,1是上架了要改为下架
      tips =
        row.publishState === 1 ? '确认下架这道题目吗?' : '确认上架这道题目吗?'
      this.$confirm(tips, '提示', { type: 'warning' })
        .then(async () => {
          let publishState
          // publishState为1是则原先是上架要改为下架
          if (row.publishState === 1) {
            // 改下架
            publishState = 0
          } else if (row.publishState === 0) {
            // 改上架
            publishState = 1
          }
          // else {
          //   publishState = row.publishState
          // }
          const res = await choicePublish({ id: row.id, publishState })
          if (!res.data.success) return
          this.$message.success('操作成功')
          this.getChoiceList()
        })
        .catch((err) => {
          return err
        })
    },

    // 审核
    open (row) {
      this.checkDialog = true
      // console.log(row)
      this.selectedQuestionId = row.id
    },
    async handleCheck () {
      if (!this.chkRemarks) {
        return this.$message.warning('请输入审核意见')
      }
      const res = await choiceCheck({
        id: this.selectedQuestionId,
        chkState: Number(this.checkRadio),
        chkRemarks: this.chkRemarks
      })
      if (!res.data.success) return
      this.$message.success('操作成功')
      this.closeChkDialog()
    },
    closeChkDialog () {
      this.checkDialog = false
      this.checkRadio = '1'
      this.chkRemarks = ''
      this.getChoiceList()
    }
  }
}
</script>

<style lang="scss" scoped>
.question-container {
  margin: 10px 0;
  padding: 0 10px;

  .btn_wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .alert {
    margin: 10px 0px;
  }

  .pagination {
    margin-top: 10px;
  }
}
.el-button--medium {
  font-size: 12px;
}
::v-deep .el-form-item--medium .el-form-item__content {
  line-height: 40px;
}
</style>
